from django.db.models import Q
from rest_framework.decorators import action
from rest_framework.generics import ListAPIView
from rest_framework.mixins import UpdateModelMixin
from rest_framework.permissions import IsAdminUser
from rest_framework.viewsets import ReadOnlyModelViewSet

from meiduo_admin.serializers.orders import OrdersSerializer, OrderSerializer, StatusSerializer
from orders.models import OrderInfo


class OrdersView(UpdateModelMixin, ReadOnlyModelViewSet):
    permission_classes = [IsAdminUser]

    def get_serializer_class(self):
        if self.action == 'list':
            return OrdersSerializer
        elif self.action == 'retrieve':
            return OrderSerializer
        else:
            return StatusSerializer

    def get_queryset(self):
        keyword = self.request.query_params.get('keyword')
        if keyword:
            orders = OrderInfo.objects.filter(Q(order_id__contains=keyword) |
                                              Q(create_time__contains=keyword) |
                                              Q(skus__sku__name__contains=keyword))
        else:
            orders = OrderInfo.objects.all()

        return orders

    @action(methods=['put'], detail=True)
    def status(self, request, pk):
        # order = self.get_object()
        # serializer = StatusSerializer(order, data=request.data)
        # serializer.is_valid(raise_exception=True)
        # serializer.save()
        # return serializer.data
        return self.update(request, pk)
